package io.renren.modules.oatools.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataSourceUtils {
    private static Logger logger = LoggerFactory.getLogger(DataSourceUtils.class);


    /**
     * 获取数据库连接
     * @param dbUrl
     * @param dbUsername
     * @param dbPassword
     * @param dbDriver
     * @return
     */
    public Connection test(String dbUrl, String dbUsername, String dbPassword, String dbDriver) {
        Connection conn = null;
        try {
            Class.forName(dbDriver);
            conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
            if (conn == null) {
                logger.error("数据库连接失败：" );
            }
        } catch (ClassNotFoundException e) {
            logger.error("数据库连接失败：驱动类不存在",e);
            return null;
        } catch (Exception e) {
            logger.error("数据库连接失败：" + e.getMessage());
            return null;
        } finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException var16) {
                logger.error(var16.toString());
            }
        }
        return conn;
    }

    /**
     * 获取数据库连接
     * @param dbUrl
     * @param dbUsername
     * @param dbPassword
     * @param dbDriver
     * @return
     */
    public Connection getConnection(String dbUrl, String dbUsername, String dbPassword, String dbDriver) {
        try {
            Class.forName(dbDriver);
            return DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        } catch (ClassNotFoundException e) {
            logger.error("数据库驱动未找到: {}", dbDriver, e);
            return null;
        } catch (SQLException e) {
            logger.error("数据库连接失败: URL={}, 用户={}", dbUrl, dbUsername, e);
            return null;
        }
    }
}